﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MTQ.Common
{
    public class ExportHelper<T> where T : class, new()
    {

        public System.IO.MemoryStream ExportWriter(List<T> listT, string[,] template)
        {
            System.IO.MemoryStream output = new System.IO.MemoryStream();
            System.IO.StreamWriter writer = new System.IO.StreamWriter(output, System.Text.Encoding.UTF8);

            int lenght = template.GetLength(0);
            for (int i = 0; i < lenght; i++)
                writer.Write(template[i, 0] + ",");
            writer.WriteLine();
            foreach (T user in listT)
            {
                for (int i = 0; i < lenght; i++)
                {
                    writer.Write(string.Format(template[i, 2], user.GetType().GetProperty(template[i, 1]).GetValue(user, null)));
                    if (i == 0)
                        writer.Write(",\"");
                    else if (i == lenght - 1)
                        writer.WriteLine();
                    else if (i == lenght - 2)
                        writer.Write("\",");
                    else
                        writer.Write("\",\"");
                }
            }
            writer.Flush();
            output.Position = 0;

            return output;
        }

        public void ExportCSVWriter(System.IO.StreamWriter writer, List<T> listT, string[,] template)
        {

            int lenght = template.GetLength(0);
            for (int i = 0; i < lenght; i++)
                writer.Write(template[i, 0] + ",");
            writer.WriteLine();
            foreach (T user in listT)
            {
                for (int i = 0; i < lenght; i++)
                {
                    writer.Write("\""+string.Format(template[i, 2], user.GetType().GetProperty(template[i, 1]).GetValue(user, null))+ "\"");
                    if (i == 0)
                        writer.Write(",");
                    else if (i == lenght - 1)
                        writer.WriteLine();
                    else if (i == lenght - 2)
                        writer.Write(",");
                    else
                        writer.Write(",");
                }
            }
            writer.Flush();
         
        }





    }
}
